//
//  QLHomeViewController.swift
//  QLadder
//
//  Created by TonyHan on 2017/11/16.
//  Copyright © 2017年 TonyHan All rights reserved.
//

import UIKit
import MJRefresh

let identifier = "hostCellIdentifier"
let kUserAccount = "userAccount"
let kUserPassword = "userPassword"

class QLHomeViewController: QLBaseViewController, VpnManagerDelegate, ConfigManagerDelegate, QLNewViewControllerDelegate, UITableViewDataSource, UITableViewDelegate {
    
    var dataArray : NSArray = []//服务器列表数据源

    @IBOutlet weak var bannerImgView: UIImageView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var connectButton: UIButton!
    
    var selectVPNIndex : NSInteger = 0
    var bannerUrl = NSString()
    
    
    var isStatusBarHidden:Bool = true
    let modelHandle : HomeVCModelHandle = HomeVCModelHandle.init()
    
    var status: VpnStatus {
        didSet {
            updateConnectButtonText(status: status)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        status = .off
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI();
        
        ConfigManager.shared.delegate = self as ConfigManagerDelegate
        VpnManager.shared.delegate = self as VpnManagerDelegate
        
        ConfigManager.shared.loadConfig()
        
        NotificationCenter.default.addObserver(self, selector: #selector(willLoginOut), name: NSNotification.Name(rawValue: "willLoginOutNotification"), object: nil)
        
        getBannerPic();
        self.modelHandle.loadUserInfo();
        
    }
    
    func setupUI() {
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
        self.tableView.tableFooterView = UIView.init();
        let refreshHeader : MJRefreshNormalHeader = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(refreshMethod))
        refreshHeader.lastUpdatedTimeLabel.isHidden = true
        self.tableView.mj_header = refreshHeader
        self.tableView.mj_header.beginRefreshing()
        
        self.connectButton.layer.cornerRadius = self.connectButton.frame.size.height / 2.0
//        self.connectButton.layer.borderWidth = 1
//        self.connectButton.layer.borderColor = QLColor.BF.cgColor
        connectButtonAnimation()
        
        isStatusBarHidden = false
        setNeedsStatusBarAppearanceUpdate()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        status = VpnManager.shared.vpnStatus
    }
    
    @objc func refreshMethod() {
        let network : BaseNetworkUtil = BaseNetworkUtil.sharedInstance();
        if let userName = UserDefaults.init().object(forKey: kUserAccount) {
            network.post(withModuleURLStr: vpnServerList, parameters: ["userName" : userName], success: { (response) in
                self.tableView.mj_header.endRefreshing()
                if let dic : NSDictionary = response as? NSDictionary {
                    if let dataArr : NSArray = dic["nodeInfo"] as? NSArray {
                        self.dataArray = dataArr;
                        self.tableView.reloadData();
                    }
                }
                
            }, failure: {(error) in
                self.tableView.mj_header.endRefreshing()
            }, withHud: true);
        }
    }
    
    func getBannerPic() {
        self.modelHandle.setupBannerImg(self.bannerImgView);
        self.modelHandle.handleBannerImgDidClickedBlock { (url) in
            self.bannerUrl = url as NSString
            self.performSegue(withIdentifier: "serverListVCToWebVCSegue", sender: self)
            NSLog(url );
        }
        self.modelHandle.handleDidLoadUserInfoBlock { (openVpn) in
            if openVpn > 0 {
                self.navigationItem.title = "服务器-付费用户"
            }else{
                self.navigationItem.title = "服务器-非付费用户"
            }
        }
    }
    
    @objc func willLoginOut() {
        if VpnManager.shared.vpnStatus != .off {
            VpnManager.shared.stopVPN();            
        }
    }
    
    func updateConnectButtonText(status: VpnStatus) {
        
        BaseNetworkUtil.sharedInstance()?.isVPNConnected = (VpnManager.shared.vpnStatus == .on)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.connectButton.isEnabled = [VpnStatus.on, VpnStatus.off].contains(status)
            if VpnManager.shared.vpnStatus == .on {
//                self.connectButton.layer.borderColor = QLColor.Color_Main.cgColor
                self.connectButton.setImage(UIImage.init(named: "connected"), for: .normal)
                self.connectButton.backgroundColor = QLColor.Color_Main.alpha(0.3);
            }else{
//                self.connectButton.layer.borderColor = QLColor.BF.cgColor
                self.connectButton.setImage(UIImage.init(named: "unconnect"), for: .normal)
                self.connectButton.backgroundColor = QLColor.BF.alpha(0.3);
            }
        }
    }
    
    @objc private func newConfig() {
        let newVC = QLNewViewController()
        newVC.hidesBottomBarWhenPushed = true
        newVC.delegate = self
        navigationController?.pushViewController(newVC, animated: true)
    }
    
    @IBAction func connectVPN(_ sender: Any) {
        if self.dataArray.count == 0 {
            HUDUtil.showStr("获取服务器列表失败")
            return
        }
        if (VpnManager.shared.vpnStatus == .off) {
            if self.modelHandle.isCanConnect() == false {
                HUDUtil.showStr("当前服务器不稳定，请稍后重试")
                return
            }
            modelHandle.uploadUserLoginLog(withIsLogin: true)
            setupVPNDataWithIndex(index: selectVPNIndex)
            VpnManager.shared.startVPN()
        } else {
            modelHandle.uploadUserLoginLog(withIsLogin: false)
            VpnManager.shared.stopVPN()
        }
    }
    
    func setupVPNDataWithIndex(index : NSInteger) {
        if let dic = (self.dataArray.object(at: index)) as? NSDictionary {
            let host = dic["serverIp"] as? String
            let port = dic["serverPort"] as? Int
            let password = dic["password"]  as? String
            let encryptMode = dic["encryptMode"] as? String
            let mode = encryptMode?.uppercased().replacingOccurrences(of: "-", with: "")
            ConfigManager.shared.saveConfig(host: host ?? "", port: String(format: "%d", port ?? "") , passwd: password ?? "", encryptMode: mode ?? "")
            ConfigManager.shared.loadConfig()
        }
    }
    
    func updateConfigUI(_ proxy: Proxy?) {
        if proxy != nil {
            connectButton.isEnabled = true
        } else {
            connectButton.isEnabled = false
        }
    }
    
    func connectButtonAnimation() {
        let animation : CABasicAnimation = self.modelHandle.getAnimation()
        self.connectButton.layer.add(animation, forKey: "zoom")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier as String, for: indexPath)
        if let dic = (self.dataArray.object(at: indexPath.row)) as? NSDictionary {
            cell.textLabel?.text = (dic["country"] as? String ?? "") + " " + (dic["city"] as? String ?? "")
        }
        
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        selectVPNIndex = indexPath.row;
        connectVPN(self.connectButton)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "serverListVCToWebVCSegue" {
            let webVC = segue.destination as! GoldenVPNWebVC;
            webVC.url = bannerUrl
        }
    }
    
}

// MARK: - VpnManagerDelegate
extension QLHomeViewController {
    func manager(_ manager: VpnManager, didChangeStatus status: VpnStatus) {
        updateConnectButtonText(status: status)
    }
}

// MARK: - ConfigManagerDelegate
extension QLHomeViewController {
    func manager(_ manager: ConfigManager, didReceivedConfig proxy: Proxy?) {
        updateConfigUI(proxy)
    }
}

// MARK: - StatusBar
extension QLHomeViewController {
    
    override var prefersStatusBarHidden: Bool {
        return self.isStatusBarHidden
    }
}

// MARK: - QLNewViewControllerDelegate
extension QLHomeViewController {
    func newViewControllerDidAddConfig(_ controller: QLNewViewController) {
        ConfigManager.shared.loadConfig()
        if (VpnManager.shared.vpnStatus == .on) {
            VpnManager.shared.stopVPN()
        }
    }
}

